package com.quan.junit;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.toolkit.StringUtils;

public class MyBatisPlusGenerator {

	private final static String dbUrl = "jdbc:mysql://localhost:3306/quan_sport?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false";
	private final static String driverClass = "com.mysql.jdbc.Driver";
	private final static String username = "quan_sport";
	private final static String password = "quan_sport";

	// 输出目录
	private final static String outputDir = "D:\\mars\\Workspaces\\eclipse\\SpringCloud\\Prod-Sprot\\quan-sport-project\\quan-sport-service-provider\\quan-sport-service-provider-upms\\src\\main\\java";

	// 页面输出目录
	private final static String viewOutputDir = outputDir + "/view/";
	
	public static void main(String[] args) {
		generate();
	}

	public static void generate() {
		//MyBatisPlusGenerator.generate("com.quan.upms");
		MyBatisPlusGenerator.generate("com.quan.aa", "tb_sys_log", "tb_upms_user");
	}

	public static void generate(String packageName, String... tableNames) {
		AutoGenerator autoGenerator = new AutoGenerator();

		// 数据源配置
		DataSourceConfig dataSourceConfig = new DataSourceConfig();
		dataSourceConfig.setDbType(DbType.MYSQL);
		dataSourceConfig.setUrl(dbUrl);
		dataSourceConfig.setUsername(username);
		dataSourceConfig.setPassword(password);
		dataSourceConfig.setDriverName(driverClass);
		dataSourceConfig.setTypeConvert(new MySqlTypeConvert(){
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                if("tinyint(1)".equals(fieldType)) { //将tinyint转换为boolean类型
                	System.out.println("转换类型：" + fieldType);
                	return DbColumnType.BASE_BOOLEAN;
                }
                // 注意！！processTypeConvert 存在默认类型转换，如果不是你要的效果请自定义返回、非如下直接返回。
                return super.processTypeConvert(fieldType);
            }
        });
		autoGenerator.setDataSource(dataSourceConfig);

		// 全局配置
		GlobalConfig config = new GlobalConfig();
		config.setOutputDir(outputDir);
		config.setActiveRecord(true);
		config.setFileOverride(true);
		// XML 二级缓存
		config.setEnableCache(false);
		// XML ResultMap
		config.setBaseResultMap(true);
		// XML columList
		config.setBaseColumnList(true);
		config.setServiceName("%sService");
		config.setAuthor("杨浩泉");
		autoGenerator.setGlobalConfig(config);

		// 策略配置
		StrategyConfig strategyConfig = new StrategyConfig();
		strategyConfig.setTablePrefix("tb_");
		strategyConfig.setSuperControllerClass("com.quan.common.web.BaseController");
		// 表名生成策略
		strategyConfig.setNaming(NamingStrategy.underline_to_camel);
		// 修改替换成你需要的表名，多个表名传数组
		if (null != tableNames) {
			strategyConfig.setInclude(tableNames);
		}
		autoGenerator.setStrategy(strategyConfig);

		// 包配置
		PackageConfig packageConfig = new PackageConfig();
		packageConfig.setParent(packageName);
		packageConfig.setController("controller");
		autoGenerator.setPackageInfo(packageConfig);
		
		// 注入自定义配置，可以在 VM 中使用 cfg.abc 设置的值
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        // 生成的模版路径，不存在时需要先新建
        File viewDir = new File(viewOutputDir);
        if (!viewDir.exists()) {
            viewDir.mkdirs();
        }
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        focList.add(new FileOutConfig("/templates/listvue.vue.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return getGeneratorViewPath(viewOutputDir, tableInfo, ".vue");
            }
        });
        cfg.setFileOutConfigList(focList);
        autoGenerator.setCfg(cfg);

		// 生成
		autoGenerator.execute();
	}
	
	 /**
     * 页面生成的文件名
     */
    private static String getGeneratorViewPath(String viewOutputDir, TableInfo tableInfo, String suffixPath) {
        String name = StringUtils.firstToLowerCase(tableInfo.getEntityName());
        String path = viewOutputDir + "/" + name + "/index"  + suffixPath;
        File viewDir = new File(path).getParentFile();
        if (!viewDir.exists()) {
            viewDir.mkdirs();
        }
        return path;
    }

}
